package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
    @Autowired
    private AuthService authService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("accredit")
    public ResponseEntity<Void> accredit(@RequestParam("username") String username, @RequestParam("password") String password , HttpServletRequest request, HttpServletResponse response) throws Exception {
        String token=authService.accredit(username,password);
        if (StringUtils.isBlank(token)){
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        //向浏览器写入cookie
        CookieUtils.setCookie(request , response, jwtProperties.getCookieName(), token, jwtProperties.getCookieMaxAge(),null,true);

        return ResponseEntity.ok().build();

    }

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue("LY_TOKEN") String s, HttpServletRequest request, HttpServletResponse response) throws Exception {
        UserInfo userinfo = JwtUtils.getInfoFromToken(s, jwtProperties.getPublicKey());
        if(null!=userinfo){
            //刷新cookie里面的字符换
            String token = JwtUtils.generateToken(userinfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());

            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token,jwtProperties.getCookieMaxAge() ,null,true );
            return  ResponseEntity.ok(userinfo);

        }


        return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();

    }

}
